pxt-calliope/libs/i2c-fram/fram.ts

56 lines
1.4 KiB
TypeScript
Raw Normal View History

2016-04-06 02:25:45 +02:00
namespace i2c_fram {
const devaddr = 0x50;
2016-04-06 04:19:27 +02:00
const memend = 0x7fff;
2016-04-06 02:25:45 +02:00
//% shim=ksrt::panic
function panic(code: number) { }
function die() { panic(142) }
export function readByte(addr: number) {
2016-04-06 04:19:27 +02:00
if (addr < 0 || addr > memend)
2016-04-06 02:25:45 +02:00
die();
let buf = pins.createBuffer(2)
buf[0] = (addr >> 8) & 0xff;
buf[1] = addr & 0xff;
pins.i2cWriteBuffer(devaddr, buf);
buf = pins.i2cReadBuffer(devaddr, 1);
return buf[0];
}
export function writeByte(addr: number, val: number) {
2016-04-06 04:19:27 +02:00
if (addr < 0 || addr > memend)
2016-04-06 02:25:45 +02:00
die();
if (val < 0 || val > 0xff)
die();
let buf = pins.createBuffer(3)
buf[0] = (addr >> 8) & 0xff;
buf[1] = addr & 0xff;
buf[2] = val;
pins.i2cWriteBuffer(devaddr, buf)
}
export function readBuffer(addr: number, length: number) {
2016-04-06 04:19:27 +02:00
if (addr < 0 || length < 0 || (addr + length) > memend)
2016-04-06 02:25:45 +02:00
die();
let buf = pins.createBuffer(length)
for (let i = 0; i < length; ++i)
buf[i] = readByte(addr + i)
return buf
}
export function writeBuffer(addr:number, buf: Buffer) {
2016-04-06 04:19:27 +02:00
if (addr < 0 || (addr + buf.length) > memend)
2016-04-06 02:25:45 +02:00
die();
for (let i = 0; i < buf.length; ++i)
writeByte(addr + i, buf[i])
}
}