Skip to content

Commit

Permalink
Updated openocd and i2c
Browse files Browse the repository at this point in the history
  • Loading branch information
Matthias Niedermaier committed Dec 15, 2023
1 parent b57b1f4 commit caa90c4
Show file tree
Hide file tree
Showing 3 changed files with 86 additions and 0 deletions.
61 changes: 61 additions & 0 deletions software/i2c.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import time
import smbus

i2c_ch = 1

# TMP102 address on the I2C bus
i2c_address = 0x20

# Register addresses
reg_temp = 0x00
reg_config = 0x01

# Calculate the 2's complement of a number
def twos_comp(val, bits):
if (val & (1 << (bits - 1))) != 0:
val = val - (1 << bits)
return val

# Read temperature registers and calculate Celsius
def read_temp():

# Read temperature registers
val = bus.read_i2c_block_data(i2c_address, reg_temp, 2)
# NOTE: val[0] = MSB byte 1, val [1] = LSB byte 2
print ("!shifted val[0] = ", bin(val[0]), "val[1] = ", bin(val[1]))

temp_c = (val[0] << 4) | (val[1] >> 4)
#print (" shifted val[0] = ", bin(val[0] << 4), "val[1] = ", bin(val[1] >> 4))
#print (bin(temp_c))

# Convert to 2s complement (temperatures can be negative)
temp_c = twos_comp(temp_c, 12)

# Convert registers value to temperature (C)
temp_c = temp_c * 0.0625

return temp_c

# Initialize I2C (SMBus)
bus = smbus.SMBus(i2c_ch)

# Read the CONFIG register (2 bytes)
val = bus.read_i2c_block_data(i2c_address, reg_config, 2)
print("Old CONFIG:", val)

# Set to 4 Hz sampling (CR1, CR0 = 0b10)
val[1] = val[1] & 0b00111111
val[1] = val[1] | (0b10 << 6)

# Write 4 Hz sampling back to CONFIG
bus.write_i2c_block_data(i2c_address, reg_config, val)

# Read CONFIG to verify that we changed it
val = bus.read_i2c_block_data(i2c_address, reg_config, 2)
print("New CONFIG:", val)

# Print out temperature every second
while True:
temperature = read_temp()
print(round(temperature, 2), "C")
time.sleep(1)
3 changes: 3 additions & 0 deletions software/openocd_rpi.cfg
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
adapter driver sysfsgpio
transport select swd

# gdb network
bindto 0.0.0.0

# Header pin numbers for SWD: 25 24
sysfsgpio swd_nums 25 24

Expand Down
22 changes: 22 additions & 0 deletions software/readI2Cpi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# i2ctest.py
# A brief demonstration of the Raspberry Pi I2C interface, using the Sparkfun
# Pi Wedge breakout board and a SparkFun MCP4725 breakout board:
# https://www.sparkfun.com/products/8736

import smbus
import time

# I2C channel 1 is connected to the GPIO pins
channel = 1

# MCP4725 defaults to address 0x60
address = 0x20


# Initialize I2C (SMBus)
bus = smbus.SMBus(channel)

# Create a sawtooth wave 16 times
data = bus.read_i2c_block_data(address, 0x0, 8)
print(data)
time.sleep(10)

0 comments on commit caa90c4

Please sign in to comment.